<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/10/29
 * Time: 10:18 PM
 */

namespace App\Library\Mall;


use App\Events\OrderEvent;
use App\Library\AuthenticatedUser;
use App\Models\Order;
use Illuminate\Http\Request;

trait SoldTrait
{
    use AuthenticatedUser;

    public function send(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->solds()->find($order_id);
        if ($order){
            $shipping_type = $request->input('shipping_type', 1);

            if ($order->shipping_status) {
                //return $this->sendResponse($order);
            }

            if ($shipping_type == 1) {
                $express_id = $request->input('express_id');
                $express_no = $request->input('express_no');

                if ($express_id && $express_no) {
                    $order->shipping->update([
                        'express_id'=>$express_id,
                        'express_no'=>$express_no,
                        'shipping_type'=>$shipping_type,
                        'updated_at'=>time()
                    ]);
                }else {
                    return $this->sendFailResponse(1, 'invalid parameter');
                }
            } else {
                $order->shipping->update([
                    'shipping_type'=>$shipping_type,
                    'updated_at'=>time()
                ]);
            }

            $order->changeToSend();

            $order->actions()->create([
                'uid'=>$this->user()->uid,
                'username'=>$this->user()->username,
                'content'=>trans('mall.delivery success'),
                'created_at'=>time()
            ]);

            event(new OrderEvent($order, 'send'));

            return $this->sendResponse($order);
        }else {
            return $this->sendFailResponse(2, 'order not found');
        }
    }

    protected function sendResponse(Order $order)
    {
        return ajaxReturn(['order'=>$order]);
    }

    protected function sendFailResponse($errcode, $errmsg)
    {
        return ajaxError($errcode, $errmsg);
    }
}
